package Demo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-07-30
 * Time: 20:37
 */
public class HashBucket2 <K,T> {
    public static final int DEFAULT_CAPACITY = 10;//默认容量
    public Node<K,T>[] array;
    public static final float LOAD_FACTOR = 0.75f;
    public int useSize;

    static class Node<K,T>{
        public K key;
        public T val;
        public Node<K,T> next;

        public Node(K key, T val) {
            this.key = key;
            this.val = val;
        }
    }

    public HashBucket2(){
        this.array = (Node<K,T>[]) new Node[DEFAULT_CAPACITY];
    }

    public void push(K key,T val){
        //求出下标
        int hash = key.hashCode();
        int index = hash % array.length;

        //遍历链表，判断是否有节点key值一样
        Node<K,T> cur = array[index];
        while(cur != null){
            if(cur.key.equals(key)){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        //头插法
        Node newNode = new Node(key,val);
        newNode.next = array[index];
        array[index] = newNode;
        useSize++;

        //求负载因子
        float loadFactor = (useSize * 1.0f) / array.length;
        //判断数组是否需要扩容
        if(loadFactor > LOAD_FACTOR){
            Expansion();
        }
    }
    //扩容
    private void Expansion(){
        Node<K,T>[] newArray = (Node<K,T>[]) new Node[2 * array.length];
        for (int i = 0; i < array.length; i++) {
            Node<K,T> cur =  array[i];
            while(cur != null){
                int hash = cur.key.hashCode();
                int newIndex = hash % newArray.length;
                Node<K,T> curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }
    //获取指定key对应的val值
    public T getVal(K key){
        int ret = key.hashCode();
        int index = ret % array.length;
        //遍历链表，判断是否有节点key值一样
        Node<K,T> cur = array[index];
        while(cur != null){
            if(cur.key.equals(key)){
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}
